from django.contrib.auth import mixins
from django.core.cache import cache
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse

from users.models import Address
# Create your views here.


from .models import Area
from meiduo_mall.utils.response_code import  RETCODE
import json
import logging
from users.models import User

logger = logging.getLogger('django')

class AddressIndex(mixins.LoginRequiredMixin,View):
    '''收获地址首页'''
    def get(self,request):
        # 这里有另一种查询写法:注意要把逻辑删除的部分给剔除了，不然前端会显示删除了的部分
        address_qs = request.user.addresses.filter(is_deleted = False)
        # default_id = request.user.get(default_id=True)
        address_list = []
        for address_model in address_qs:
            address_list.append({
                # 此id必须加进去，为每个地址id，以后设置为默认地址的时候，前端需要携带此id
                'id':address_model.id,
                'title': address_model.title,
                'receiver': address_model.receiver,
                'province_id': address_model.province_id,
                'province': address_model.province.name,
                'city_id': address_model.city_id,
                'city': address_model.city.name,
                'district_id': address_model.district_id,
                'district': address_model.district.name,
                'place': address_model.place,
                'mobile': address_model.mobile,
                'tel': address_model.tel,
                'email': address_model.email,
            })
        # 注意此处传的是id，两边保持一致
        default_address_id = request.user.default_address_id
        # 注意，此处必须传default_id的值
        return render(request,'user_center_site.html',{'addresses':address_list,'default_address_id':default_address_id})

class AddAddress(View):
    '''新增地址三级联动'''
    def get(self,request):
        area_id = request.GET.get('area_id')
        if not area_id:
            province_list = cache.get('province')
            if not province_list:
                try:
                    # 注意此处的为空查询：parent__isnull=True
                    province_qs = Area.objects.filter(parent__isnull=True)
                    province_list =[]
                    for province_models in province_qs:
                        # 根据前端收到列表后再取对面的id和name数据，所以此处得设置为id和name为key的字典形式
                        province_list.append({'id':province_models.id,'name':province_models.name})
                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code':RETCODE.DBERR,'errmsg':'省份数据错误'})
                cache.set('province',province_list,3600)
            return JsonResponse({'code':RETCODE.OK,'province_list':province_list})
        else:
            data = cache.get('city%s'%area_id)
            if not data:
                try:
                    city_qs = Area.objects.filter(parent = area_id)
                    parent_name = Area.objects.get(id = area_id)
                    city_list = []
                    for city_models in city_qs:
                        city_list.append({'id':city_models.id,'name':city_models.name})
                    data = {
                        'id':area_id,

                        #  注意，此处必须取出parent_name中的name，因为parent_name是一个qs对象，不能直接使用，json格式汇报错
                        'name': parent_name.name,
                        'subs':city_list,
                    }
                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code':RETCODE.DBERR,'errmsg':'市区数据错误'})
                cache.set('city%s' % area_id,data,3600)
            return JsonResponse({'code':RETCODE.OK,'sub_data':data})





